<template>
  <div class="page-select">
    <a-input v-model:value="valueIpt" id="iptBox" placeholder="请输入"
      style="width: 100%;background:0;color: #fff;border: 0;" v-show="isFocus" @change="iptValChange" />
    <div @click="slcWrapClick">
      <a-select v-show="!isFocus" :filter-option="false" v-model:value="valueSlc" mode="multiple" style="width: 100%"
        placeholder="请输入" @search="handleChange" @select="slcList" @deselect="deSlcList" :notFoundContent="null"
        @dropdownVisibleChange="dropdownVisibleChange" :open="isOpen" @focus="focusFunc">

        <a-select-option v-for="(item, index) in roadNewList" :key="item[id]" :value="item.id">
          {{ item[labelKey] }}-{{ item.jdcds }}车道 - {{ item.finished }}
        </a-select-option>

      </a-select>
    </div>
    <!-- <div ref="buttonRef" class="page-select__input" @click="focusInput">
      <el-input v-model="roadName" @input="changeVal" placeholder="请输入" clear />
      <el-icon class="flex-shrink-0" size="18" color="#dcdfe6">
        <ArrowUp v-if="isShow" />
        <ArrowDown v-else />
      </el-icon>
    </div>

    <el-popover
      ref="popoverRef"
      :virtual-ref="buttonRef"
      trigger="click"
      virtual-triggering
      :width="popoverWidth"
      placement="bottom"
      :show-arrow="false"
      popper-class="!p-0"
      :offset="0"
      @after-leave="isShow = false"
      @after-enter="isShow = true"
    >
      <div class="transition-box input-box">
        <ul>
          <li v-for="item in roadNewList" :key="item[valueKey]" class="lis flex_between" @click.stop="handleItem(item)">
            <span>{{ item[labelKey] }}</span>
            <span v-if="roadIds.includes(item.id)">...</span>
          </li>
        </ul>
        <el-pagination
          v-if="data.length"
          layout="prev, pager, next"
          small
          v-bind="pagination"
          :pager-count="5"
          @current-change="pagination.onCurrentChange"
        />
      </div>
    </el-popover> -->
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs, ref, onMounted, watch, computed } from 'vue';
import { getRoadInfoByKey, getRoadBasicByIds, getRoadJdcdsByKey } from '@/api/basic';
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue';
import { message } from 'ant-design-vue';
import { useMapStore } from '@/store/modules/map';
// import { debounce } from '@/utils/index.ts'
import { debounce } from 'lodash-es';
export default defineComponent({
  name: 'PageSelect',
  props: {
    data: {
      type: Array,
      default() {
        return [];
      },
    },
    modelValue: {
      type: String,
      default: '',
    },
    label: {
      type: String,
      deafult: '',
    },
    labelKey: {
      type: String,
      default: 'label',
    },
    valueKey: {
      type: String,
      default: 'value',
    },
    pagination: {
      type: Object,
      deafult() {
        return {};
      },
    },
    slcJdcds: {
      type: [Number, String],
      default: "",
    },
  },
  emits: ['update:modelValue', 'update:label', 'page-change', 'change', 'iptChange', "getSearchRoadList", "getSearchJdcdsList"],
  setup(props, { emit }) {
    const popoverWidth = ref('');
    const mapStore = useMapStore();
    const isClearList = computed(() => mapStore.slcList);
    const state = reactive({
      isShow: false,
      popoverRef: null,
      buttonRef: null,
      roadName: [],
      roadNameList: [],
      roadIds: [],
      roadNewList: [],
      valueSlc: [],
      valueIpt: null,
      isOpen: true,
      isFocus: true,
      searchName:'',
    });

    watch(
      isClearList,
      () => {
        // console.log("---==>",isClearList?.value);
        state.valueSlc = []
        state.isFocus = true
        // state.roadNewList = []
      },
      {
        deep: true,
      },
    );
    watch(
      () => props.slcJdcds, (val) => {
        // console.log("state.searchName",state.searchName);
        // console.log("val", val);
        getRoadList({
          roadName:state.searchName,
          jdcds:val
        })
      }
    )
    // 获得焦点 显示下拉框
    const focusInput = () => {
      popoverWidth.value = state.buttonRef.scrollWidth;
    };
    const dropdownVisibleChange = (open) => {
      // console.log("open",open);
      state.isOpen = open

    }

    // 点击 li 选择
    const handleItem = (item) => {
      // console.log("item", item);
      emit('update:modelValue', item[props.valueKey]);
      emit('update:label', item[props.labelKey]);

      emit('change', {
        value: item[props.valueKey],
        label: item[props.labelKey],
        data: item,
      });

      // if(state.roadNameList.length > 1){
      state.roadName = []
      // }
      // console.log("-----",state.roadName);
      if (!state.roadIds.includes(item.id)) {
        state.roadName = [...state.roadNameList, item[props.labelKey]]
        state.roadNameList.push(item[props.labelKey])
        state.roadIds.push(item.id)
        // state.roadIds = [...state.roadIds,item.id]

        // console.log("state.roadNameList",state.roadNameList);
      } else {
        let arrIndex = state.roadIds.findIndex(itemIds => { return item.id == itemIds })
        state.roadIds.splice(arrIndex, 1)
        // console.log("state.roadName",state.roadName);
        state.roadNameList.splice(arrIndex, 1)
        // console.log("arrIndex",arrIndex);
        state.roadName = state.roadNameList
      }
      // console.log("state.roadIds", state.roadIds);
      // 多选时
      // getRoadBasicByIds({ids:state.roadIds.join()}).then(resN=>{
      //   // console.log("resN",resN);
      //   state.roadNewList = resN
      // })
      // onClickOutside();
    };

    const handleChange = (v) => {
      // console.log("v",v);
      if (!v) {
        state.roadNewList = []
        return
      }
      state.searchName = v
      getRoadList({ roadName: v })
      getJdcdsList({ roadName: v })
    }
    const getJdcdsList = debounce((val) => {
      getRoadJdcdsByKey(val).then(resJ => {
        emit("getSearchJdcdsList", resJ)
      })
    }, 500)
    const focusFunc = () => {
      // state.isFocus = true
      // let iii = document.getElementById("iptBox")
      // setTimeout(() => {
      //   iii.focus()
      // }, 300);
    }
    const iptValChange = (e) => {
      // console.log("e",e.target);
      state.searchName = e.target.value
      getJdcdsList({ roadName: e.target.value })
      getRoadList({ roadName: e.target.value })
    }
    const slcList = (sList) => {
      emit('change', {
        // value: item[props.valueKey],
        // label: item[props.labelKey],
        data: { id: sList },
      });
      // console.log("valueSlc", state.valueSlc);
      mapStore.setSlcList(true)
      emit('iptChange', state.valueSlc);
    }
    const deSlcList = () => {
      // console.log("valueSlc", state.valueSlc);
      emit('iptChange', state.valueSlc);
    }
    const changeVal = (val) => {
      // getJdcdsList({roadName:val})
      // emit('iptChange', val);
      //单选时
      // getRoadList({roadName:val})
    }
    const onClickOutside = () => {
      state.popoverRef.hide();
    };
    const getRoadList = debounce((data) => {


      getRoadInfoByKey(data).then(resN => {
        // console.log("resN",resN);
        state.roadNewList = []
        state.roadNameList = []
        state.roadNewList = resN
        emit("getSearchRoadList", resN)
        if (resN?.length) {
          state.isOpen = false
          state.valueIpt = null
          state.isFocus = false
          setTimeout(() => {
            slcWrapClick()
          }, 300);
        } else {
          state.valueIpt = null
          state.valueSlc = []
          message.warn("暂无数据...")
        }
      })
    }, 500)
    const slcWrapClick = () => {
      dropdownVisibleChange(true)
    }

    onMounted(() => {

    })
    return {
      ...toRefs(state),
      ArrowDown,
      ArrowUp,
      focusInput,
      popoverWidth,
      handleItem,
      changeVal,
      handleChange,
      slcList,
      deSlcList,
      dropdownVisibleChange,
      iptValChange,
      slcWrapClick,
      focusFunc,
    };
  },
});
</script>

<style lang="less" scoped>
.page-select__input {
  position: relative;
  height: 36px;
  border: 1px solid #1c2d4c;
  border-radius: 3px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 10px;
  overflow: hidden;
  color: #fff;
  cursor: pointer;
  background-color: #122034;
}

.input-box {
  position: relative;
}

.form_items {
  height: 40px;
  width: 100%;
  line-height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  justify-content: space-between;
  cursor: pointer;
}

.is-disabled {
  background-color: var(--el-disabled-bg-color);
  color: var(--el-disabled-text-color);
  box-shadow: 0 0 0 1px var(--el-disabled-border-color) inset;
  cursor: no-drop;
}

.transition-box {
  width: 100%;
  height: 250px;
  background: url(@/assets/images/components/customDatePicker/bg1.png) no-repeat;
  background-size: 100% 100%;

  ul {
    height: 200px;
    padding: 0;
    // margin: 10px 0 0 0;
    overflow-y: auto;
    list-style: none;

    /* 滚动条凹槽的颜色，还可以设置边框属性 */
    &::-webkit-scrollbar-track-piece {
      background-color: #122034;
    }

    /* 滚动条的设置 */
    &::-webkit-scrollbar-thumb {
      background-color: #2c6686;
    }

    /* 滚动条鼠标移上去 */
    &::-webkit-scrollbar-thumb:hover {
      background-color: #2c6686;
    }

    .lis {
      line-height: 35px;
      cursor: pointer;
      padding: 0 20px;
      color: #fff;

      &:hover {
        background-color: rgba(#fff, 0.5);
        border-radius: 0;
      }
    }
  }
}

:deep(.el-input__wrapper) {
  height: 40px;
  font-size: 14px;

  .el-input__inner {
    font-family: Source Han Sans CN;
    color: #1f2d3d;
  }
}

:deep(.el-input-group__append) {
  height: 40px;
}

.el-pagination {
  --el-pagination-bg-color: transparent;
  --el-pagination-button-color: #fff;
  --el-pagination-button-disabled-bg-color: transparent;

  justify-content: center;
  margin-top: 10px;
}

:deep(.ant-select-selection-item) {
  background: #333;
}

:deep(.ant-select-selector .ant-select-selection-search-input) {
  color: #fff;
}

:deep(.ant-select-dropdown-empty) {
  display: none;
}
</style>
